﻿
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Data;


namespace V5_EaspLibs.Utility {
    public class JsonHelper {
        /// <summary>
        /// 是否成功   
        /// </summary>
        public bool Success {
            get {
                return count > 0;
            }
        }
        private string errorMsg = "";
        /// <summary>
        /// 错误提示信息   
        /// </summary>
        public string ErrorMsg {
            get {
                return errorMsg;
            }
            set {
                errorMsg = value;
            }
        }
        private int count = 0;
        /// <summary>
        /// 总记 
        /// </summary>
        public int Count {
            get {
                return count;
            }
            set {
                count = value;
            }
        }
        private List<string> arrData = new List<string>();

        #region 对象与对象之间分割符
        public void addItemOk() {
            arrData.Add("<br>");
        }
        #endregion

        #region 在数组里添加key,value
        public void addItem(string name, string value) {
            arrData.Add("\"" + name + "\":" + "\"" + value + "\"");
        }
        #endregion

        #region 返回组装好的json字符串
        public override string ToString() {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.Append("\"count\":\"" + count + "\",");
            sb.Append("\"error\":\"" + errorMsg + "\",");
            sb.Append("\"success\":\"" + (Success ? "true" : "") + "\",");
            sb.Append("\"data\":[");

            int index = 0;
            sb.Append("{");
            if (arrData.Count <= 0) {
                sb.Append("}]");
            }
            else {
                foreach (string val in arrData) {
                    index++;

                    if (val != "<br>") {
                        sb.Append(val + ",");
                    }
                    else {
                        sb = sb.Replace(",", "", sb.Length - 1, 1);
                        sb.Append("},");
                        if (index < arrData.Count) {
                            sb.Append("{");
                        }
                    }

                }
                sb = sb.Replace(",", "", sb.Length - 1, 1);
                sb.Append("]");
            }

            sb.Append("}");
            return sb.ToString();

        }
        #endregion
    }
}
